import React from 'react';
import {
  StyleSheet,
  View,
  TextInput,
  Text,
  Image,
  // Button,
  ScrollView,
  FlatList,
  List,
  TouchableHighlight,
  TouchableOpacity,
  Dimensions,
  Keyboard
} from 'react-native';

import realm from '../models/realm'
import Moment from 'react-moment';
let { height, width } = Dimensions.get('window');
let moment = require('moment');
import { Order } from '../classObject';
import { printTicket } from '../printData'
import ScrollableTabView, { DefaultTabBar } from 'react-native-scrollable-tab-view';
import PopupDialog, { SlideAnimation } from 'react-native-popup-dialog';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/Ionicons';
import Grid from 'react-native-grid-component';
import { Card, ListItem, Button, FormLabel, FormInput } from 'react-native-elements'
// import { watch } from 'fs';
const slideAnimation = new SlideAnimation({
  slideFrom: 'bottom',
});

export default class OrderList extends React.Component {
  constructor(props) {
    super(props);
    this._onPressButton = this._onPressButton.bind(this)
    this.updateUI = this.updateUI.bind(this)
    this.orders = realm.objects('Order').sorted('id')
    this.state = {
      tables: Array.prototype.slice.call(realm.objects('Table').filtered('name != "" AND type != "object"').sorted('name')).sort((a, b) => a.name.localeCompare(b.name)),
      totalTakeAway: realm.objects('Order').filtered('type = "takeAway" AND closed = false').length,
      totalBar: realm.objects('Order').filtered('type = "bar" AND closed = false').length,
      totalDelivery: realm.objects('Order').filtered('type = "delivery" AND closed = false').length,
      config: realm.objects('Config')[0],
      orderSit: realm.objects('Order').filtered('type = "sit" AND closed = false').sorted('createdAt', true),
      ordertakeAway: realm.objects('Order').filtered('type = "takeAway" AND closed = false').sorted('createdAt', true),
      orderBar: realm.objects('Order').filtered('type = "bar" AND closed = false').sorted('createdAt', true),
      orderDelivery: realm.objects('Order').filtered('type = "delivery" AND closed = false').sorted('createdAt', true),
      sitNumber: '',
      nbCustomer: '',
      lastOrderId: realm.objects('currentOrderId')[0].id,
    }
    realm.addListener('change', this.updateUI);

  }

  componentWillUnmount() {
    realm.removeAllListeners();
  }

  updateUI() {
    this.setState({
      orderSit: realm.objects('Order').filtered('type = "sit" AND closed = false').sorted('createdAt', true),
      ordertakeAway: realm.objects('Order').filtered('type = "takeAway" AND closed = false').sorted('createdAt', true),
      orderBar: realm.objects('Order').filtered('type = "bar" AND closed = false').sorted('createdAt', true),
      totalTakeAway: realm.objects('Order').filtered('type = "takeAway" AND closed = false').length,
      totalBar: realm.objects('Order').filtered('type = "bar" AND closed = false').length,
      lastOrderId: realm.objects('currentOrderId')[0].id,
    })
  }

  _renderItem = (item, i) => {
    let hour = moment(item.createdAt).format("kk");
    let min = moment(item.createdAt).format("mm");
    return (
      <View style={styles.item} key={item.id}>
        <TouchableOpacity style={{ flexDirection: 'row', flex: 1 }} onPress={() => this._onPressButton(item.id)}>
          <View style={styles.containerNumberFalse}>
            <Text style={styles.itemNumberNow}>{item.table} / cv: {item.nbCustomer}</Text>
          </View>
          <View style={styles.containerItemA}>
            {<Text style={styles.itemPrice}>{hour}H{min}</Text>}
            {<Text style={styles.itemPrice}>{item.totalTtc.toFixed(2)} €</Text>}
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  _onPressButton(order) {
    const { navigate } = this.props.navigation
    navigate('OrderDetail', {
      orderId: order.id,
      refresh: () => {
        this.forceUpdate();
      }
    })
  }


  newOrder(orderType) {

    const { navigate } = this.props.navigation
    currentOrderId = realm.objects('currentOrderId')[0].currentOrderId;
    if (orderType == 'takeAway') {
      var newOrder = new Order(currentOrderId, 'takeAway');
      newOrder.table = 'E' + (this.state.totalTakeAway + 1)
      newOrder.nbPrinted = 1
      newOrder.userId = 1//this.props.currentUser.id
      newOrder.userName = 'Gerant'//this.props.currentUser.name
      // newOrder.deviceId = this.state.config.deviceId
      // newOrder.appVersion = this.state.config.appVersion
      // newOrder.ticketHeaderId = this.state.config.ticketHeaderId
      // newOrder.ticketFooterId = this.state.config.ticketFooterId
      newOrder.deviceId = 1
      newOrder.appVersion = '1'
      newOrder.ticketHeaderId = 1
      newOrder.ticketFooterId = 1
      realm.write(() => {
        realm.create('Order', newOrder);
        realm.create('currentOrderId', {id:1, currentOrderId:currentOrderId+1}, true)
      })
      navigate('Order', { orderId: newOrder.id,isRefresh: true, refresh:()=>{
        this.forceUpdate();
      } })
    }
    else if (orderType == 'sit') {
      //this.setState({sitNumber: '', nbCustomer: ''})
      this.keyboardDialog.show()
      //  this.refs.sitNumber.focus()
    }
  }

  newSitOrder(table) {
    currentOrderId = realm.objects('currentOrderId')[0].currentOrderId;
    const { navigate } = this.props.navigation
    var newOrder = new Order(currentOrderId, 'sit');
    newOrder.table = table.name
    newOrder.nbPrinted = 1
    newOrder.userId = 1//this.props.currentUser.id
    newOrder.userName = 'Gerant'//this.props.currentUser.name
    newOrder.deviceId = this.state.config.deviceId
    newOrder.appVersion = this.state.config.appVersion
    newOrder.ticketHeaderId = this.state.config.ticketHeaderId
    newOrder.ticketFooterId = this.state.config.ticketFooterId
    realm.write(() => {
      realm.create('Order', newOrder)
      realm.create('Table', { id: table.id, idOrder: newOrder.id }, true);
      realm.create('currentOrderId', {id:1, currentOrderId:currentOrderId+1}, true)
    })

    navigate('orderView', { orderId: newOrder.id })
    this.tableListDialog.dismiss()
  }

  newSitOrderStep2() {
    this.keyboardDialog.dismiss();
    Keyboard.dismiss();
    var reg = new RegExp('^[0-9]+$');
    if (!reg.test(this.state.sitNumber)) { alert('桌号'); return }
    if (!reg.test(this.state.nbCustomer)) { alert('人数'); return }
    const { navigate } = this.props.navigation
    var idOrder = realm.objects('currentOrderId')[0].currentOrderId;;
    var newOrder = new Order(idOrder, 'sit');
    newOrder.table = this.state.sitNumber
    newOrder.nbCustomer = parseInt(this.state.nbCustomer)
    newOrder.userId = 1//this.props.currentUser.id
    newOrder.userName = 'Gerant'//this.props.currentUser.name
    newOrder.deviceId = 1
    newOrder.totalTtc = 0.00
    newOrder.appVersion = '1'
    newOrder.ticketHeaderId = 1
    newOrder.ticketFooterId = 1
    realm.write(() => {
      realm.create('Order', newOrder, true)
      realm.create('currentOrderId', {id:1, currentOrderId:idOrder+1}, true)
    })

    navigate('Order', { orderId: newOrder.id })
    this.setState({ sitNumber: '', nbCustomer: '' })
  }
  _renderItemOrder = ({ item, index }) => {
    <View style={{ height: '100%', width: '100%', flexDirection: "row", alignItems: 'flex-start', backgroundColor: 'white' }}>
      <Text style={{ flex: 1, color: 'black', fontSize: 18 }}>{index}</Text>
      <Text style={{ flex: 1, color: 'red', fontSize: 18 }}>{item.priceTtc.toFixed(2)}€</Text>
      <Text style={{ color: 'black', fontSize: 18 }}>{item.quantity}</Text>
    </View>
  }
  _renderItemDetail = ({ item, index }) => {
    return (
      <View style={styles.containerBasket}>
        <View style={{ flexDirection: "row", flex: 1, borderWidth: 0, backgroundColor: 'white', padding: 5 }}>
          <View style={{ flex: 1, flexDirection: "row", alignItems: 'center' }}>
            {/* todo:// 菜品*/}
            <Text style={{ flex: 1, color: 'black', fontSize: 18 }}>{item.name}</Text>
            <Text style={{ color: 'black', fontSize: 18 }}>{item.quantity}</Text>
          </View>

        </View>
      </View>
    )
  }

  _renderItemLeft = ({ item }) => (
    <Card
      key={item.id}
      title={'桌号: ' + item.table}
    >
      <TouchableOpacity onPress={() => {
        this._onPressButton(item);
      }}>
        <View style={{ flex: 1 }}>
          <Text style={{ color: 'black', fontSize: 18 }}>订单号：{item.id}</Text>
          <Text style={{ color: 'black', fontSize: 18 }}>金额：{item.totalTtc.toFixed(2)}</Text>
          <Text style={{ color: 'black', fontSize: 18 }}>人数：{item.nbCustomer}</Text>
        </View>
      </TouchableOpacity>
    </Card>
  );
  _renderItemRight = ({ item }) => (
    <Card
      key={item.id}
      title={'打包: ' + item.table}
    >
      <TouchableOpacity onPress={() => {
        this._onPressButton(item);
      }}>
        <View style={{ flex: 1 }}>
          <Text style={{ color: 'black', fontSize: 18 }}>订单号：{item.id}</Text>
          <Text style={{ color: 'black', fontSize: 18 }}>金额：{item.totalTtc.toFixed(2)}</Text>
        </View>
      </TouchableOpacity>
    </Card>
  );
  render() {
    const { navigate } = this.props.navigation;
    // let leftOrders=[]; 
    // let rigntOrders=[];
    // for(var i =0; i< this.state.orderSit.length; i++){
    //   var order = this.state.orderSit[i]; 
    //  // var titleText = '桌号: ' + order.table;
    //   if(order.id % 2 == 0){
    //     leftOrders.push(order);

    //   }else{
    //     rigntOrders.push(order);
    //   }

    // }

    // for(var i =0; i< this.state.ordertakeAway.length; i++){
    //   var order = this.state.ordertakeAway[i]; 
    //  // var titleText = '桌号: ' + order.table;
    //   if(order.id % 2 == 0){
    //     leftOrders.push(order);

    //   }else{
    //     rigntOrders.push(order);
    //   }

    // }

    return (
      <View style={styles.container}>
        <View style={{ flex: 1 }}>
          <ScrollView contentContainerStyle={styles.productContainer} scrollEnabled={true}>
            <View style={{ flex: 1 }}>
              <FlatList
                data={this.state.orderSit}
                extraData={this.state}
                keyExtractor={(item) => item.id}
                renderItem={this._renderItemLeft}
              />
            </View>
            <View style={{ flex: 1 }}>
              <FlatList
                data={this.state.ordertakeAway}
                extraData={this.state}
                keyExtractor={(item) => item.id}
                renderItem={this._renderItemRight}
              />
            </View>
          </ScrollView>
        </View>

        <PopupDialog ref={(tableListDialog) => { this.tableListDialog = tableListDialog; }}
          dialogAnimation={slideAnimation}>

          <View style={{ backgroundColor: 'white', height: height / 1.4, width: width }}>
            <ScrollView
              pagingEnabled={true}
              horizontal={false}
              showsHorizontalScrollIndicator={false}
              bounces={false}
              onScroll={this.handleTableScroll}
              scrollEventThrottle={16}
            >
              <View style={styles.scrollView}>
                {
                  this.state.tables.map((table, idx) => (

                    <TouchableOpacity key={idx}
                      style={[styles.square, table.idOrder != 0 && { backgroundColor: 'red' }]}
                      onPress={() => this.newSitOrder(table)}
                      disabled={table.idOrder != 0 ? true : false}>
                      <Text style={styles.tableNumber}>{table.name}</Text>
                    </TouchableOpacity>

                  ))
                }
              </View>
            </ScrollView>
          </View>
        </PopupDialog>

        <PopupDialog ref={(OrderIdDialog) => { this.OrderIdDialog = OrderIdDialog; }}
          dismissOnTouchOutside={false}
          dialogAnimation={slideAnimation}>

          <View style={{ flexDirection: 'row', paddingTop: 5 }}>
            <Button
              buttonStyle={{ backgroundColor: 'red', width: width / 2.5, }}
              large
              title='取消'
              onPress={() => { this.OrderIdDialog.dismiss(); }}
            />
            <Button
              buttonStyle={{ backgroundColor: 'red', width: width / 2.5 }}
              large
              title='确认'
              onPress={() => { 
                var reg = new RegExp('^[0-9]+$');
                if (!reg.test(this.state.setOrderId)) { alert('订单号必须是数字'); return }
                if( parseInt(this.state.setOrderId) <= this.state.lastOrderId ){
                  alert('输入号码小于当前存在的订单号，请先结算所有订单'); return
                }
                var current = parseInt(this.state.setOrderId);
                realm.write(() => {
                  realm.create('currentOrderId', {id:1, currentOrderId: current}, true)
                })
                Keyboard.dismiss();
                this.OrderIdDialog.dismiss();
              }}
            />
          </View>
          <FormLabel>订单号</FormLabel>
          <FormInput
            onChangeText={(text) => {this.setState({setOrderId:text})}}
            placeholder={realm.objects('currentOrderId')[0].currentOrderId.toString()}
            defaultValue={realm.objects('currentOrderId')[0].currentOrderId.toString()}
            keyboardType="numeric"
          />
        </PopupDialog>

        <PopupDialog ref={(keyboardDialog) => { this.keyboardDialog = keyboardDialog; }}
          dismissOnTouchOutside={false}
          dialogAnimation={slideAnimation}
        >
          <View style={{ flexDirection: 'row', paddingTop: 5 }}>
            <Button
              buttonStyle={{ backgroundColor: 'red', width: width / 2.5, }}
              large
              title='取消'
              onPress={() => { this.keyboardDialog.dismiss(); }}
            />
            <Button
              buttonStyle={{ backgroundColor: 'red', width: width / 2.5 }}
              large
              title='确认'
              onPress={() => { this.newSitOrderStep2(); }}
            />
          </View>
          <FormLabel>桌号</FormLabel>
          <FormInput
            onChangeText={(text) => this.setState({ sitNumber: text })}
            placeholder="桌号"
            defaultValue={this.state.sitNumber}
            keyboardType="numeric"
            ref='sitNumber'
          />
          <FormLabel>人数</FormLabel>
          <FormInput
            ref='nbCustomer'
            style={{ fontSize: 70, textAlign: 'center', flexDirection: 'row', flex: 1 }}
            placeholder="人数"
            keyboardType="numeric"
            defaultValue={this.state.nbCustomer}
            onChangeText={(text) => this.setState({ nbCustomer: text })}
          />

        </PopupDialog>

        <ActionButton buttonColor="rgba(231,76,60,1)" offsetY={300} onPress={() => this.newOrder("sit")} icon={<Icon name="md-cart" style={{ color: 'white', fontSize: 15 }} >点餐</Icon>}>
        </ActionButton >
        <ActionButton offsetY={200} buttonColor="#9b59b6" onPress={() => this.newOrder("takeAway")} icon={<Icon name="md-paper" style={{ color: 'white', fontSize: 15 }} >打包</Icon>}>
        </ActionButton>
        <ActionButton offsetY={100} buttonColor="#3498db" icon={<Icon name="md-hammer" style={{ color: 'white', fontSize: 15 }} >设置</Icon>}>
          <ActionButton.Item buttonColor='orange' title="菜单" onPress={() => navigate('Product')}>
            <Icon name="md-barcode" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item buttonColor='#9b59b6' title="打印机" onPress={() => navigate('Printer')}>
            <Icon name="md-print" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item buttonColor='#3498db' title="店消息" onPress={() => { navigate('TicketHeader') }}>
            <Icon name="md-notifications-off" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item buttonColor='#1abc9c' title="小票" onPress={() => { navigate('TicketFooter') }}>
            <Icon name="md-color-palette" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item buttonColor='#1abc9c' title="结算" onPress={() => { navigate('Coloturer') }}>
            <Icon name="md-color-palette" style={styles.actionButtonIcon} />
          </ActionButton.Item>
          <ActionButton.Item buttonColor='#1abc9c' title="订单号" onPress={() => {  this.OrderIdDialog.show()}}>
            <Icon name="md-color-palette" style={styles.actionButtonIcon} />
          </ActionButton.Item>
        </ActionButton>
        <PopupDialog ref={(orderCurrent) => { this.orderCurrent = orderCurrent; }}
          dialogAnimation={slideAnimation}
          height={0.9}
        >
          <View tabLabel={"购物"} style={styles.tabLabelStyle2}>
            <FlatList
              style={styles.FlatListBasket}
              data={this.state.basketProducts}
              renderItem={this._renderItem}
              keyExtractor={(item, index) => index}
              extraData={this.state}
            />

            <View style={{ flex: 0.1, flexDirection: "row", alignItems: 'center' }}>
              {/* todo:// 菜品*/}
              <Text style={{ color: 'black', fontSize: 18 }}>共</Text>
              {/* <Text style={{color: 'red', fontSize: 18}}>{totalProducts}</Text>  */}
              <Text style={{ color: 'black', fontSize: 18 }}>菜品</Text>
              {/* <Text style={{color: 'red', fontSize: 18, justifyContent:'flex-start'}}>  {this.order.totalTtc.toFixed(2)}€</Text> */}
              <Button
                buttonStyle={{ flex: 1, backgroundColor: 'green', justifyContent: 'flex-end' }}
                large
                title='厨房'
                onPress={() => printKitchen({}, this.order)} />
              <Button
                buttonStyle={{ flex: 1, backgroundColor: 'green', justifyContent: 'flex-end' }}
                large
                title='返回'
                onPress={() => this.orderCurrent.dismiss()} />
            </View>
          </View>


        </PopupDialog>
      </View>



    );
  }
}


const styles = StyleSheet.create({

  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'flex-start',
    backgroundColor: 'white'
  },
  FlatListBasket: {
    height: '100%',
    backgroundColor: 'gray',
  },
  containerNumberFalse: {
    height: width / 7,
    flex: 1,
    justifyContent: 'center',
    flexDirection: 'column',
  },
  FlatListBasket: {
    height: '100%',
    backgroundColor: 'blue',
  },

  containerItemA: {
    flex: 2,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
  },

  item: {
    flex: 1,
    justifyContent: 'space-between',
    marginLeft: 10,
    fontSize: 24,
    fontWeight: 'bold',
    color: "white"
  },
  item: {
    flex: 1,
    height: 160,
    margin: 1
  },
  list: {
    flex: 1
  },
  productContainer: {
    paddingBottom: 0,
    flex: 20,
    marginTop: -20,
    flexDirection: 'row'
  },
  itemPrice: {
    flex: 1,
    justifyContent: 'space-between',
    textAlign: "right",
    fontSize: 22,
    fontWeight: 'bold',
    color: "black"
  },

  printerButton: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'black'
  },

  printerImg: {
    height: 40,
    width: 40,
    tintColor: 'white'
  },

  itemStyleFinish: {
    flex: 4,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  flexListFinished: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderWidth: 1,
    width: width
  },
  flexListNow: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderWidth: 1,
    width: width,
  },
  itemNumberNow: {
    fontSize: 22,
    fontWeight: 'bold',
    color: 'black',
    textAlign: 'center',
  },

  containerback: {
    backgroundColor: 'white',
    flex: 1,
  },

  FlatListHome: {
    backgroundColor: 'white',
    flexDirection: 'column',
    flexWrap: 'wrap',
    flex: 1,
  },

  // Button "Sur Place" "Emportée"

  containerButtonHome: {
    flex: 1,
    flexDirection: 'row',
    borderWidth: 1,
    height: height / 160,
  },

  containerButtonHomePlace: {
    borderRadius: 5,
    borderWidth: 1,
    flex: 1,
    flexDirection: 'row',
    height: height / 10,
  },

  containerButtonHomeEmportee: {
    borderRadius: 5,
    borderWidth: 1,
    flex: 1,
    flexDirection: 'row',
    height: height / 10,
    width: width / 10,
    alignItems: 'stretch',
  },

  buttonHomePlace: {
    flex: 1,
    backgroundColor: '#2B98F0',
    alignItems: 'center',
    flexDirection: 'row',
    borderRadius: 5,
  },

  buttonHomeEmportee: {
    flex: 1,
    backgroundColor: '#2B98F0',
    alignItems: 'center',
    flexDirection: 'row',
    borderRadius: 5,
  },

  textButtonHomePlace: {
    flex: 1,
    color: 'white',
    flexDirection: 'row',
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 20,
  },

  textButtonHomeEmportee: {
    flex: 1,
    color: 'white',
    flexDirection: 'row',
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 20,
  },

  // Other


  tabLabelStyle: {
    flex: 1,
    flexDirection: 'column',
  },

  tableList: {
    flex: 1,
    flexDirection: 'row',
  },

  scrollView: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
  },

  square: {
    width: (width / 3) - 12,
    height: 100,
    borderWidth: 2,
    borderColor: 'black',
    margin: 6,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },

  tableNumber: {
    fontSize: 33,
    color: 'black',
    textAlign: 'center'
  },

  letter: {
    fontSize: 40,
    fontWeight: 'bold',
    color: 'black',
    textAlign: 'center'
  },

  buttonOk: {
    fontSize: 60,
    marginTop: 20,
    textAlign: "center",
  }

});
